<script setup>
import {useRouter} from "vue-router";
import {HTTP} from '@/api/HTTP.js'
import {ref, onMounted, onBeforeMount} from "vue";
import {ElMessage} from "element-plus";

const router = useRouter()
const handleBack = () => {
  router.back()
}

// 用户信息数据 密保数据
const usernameData = ref({})
const project = ref('')
let createQueDialog = ref(false);

const newQue= ref({
  que:"",
  ans:""
})

onBeforeMount(async () => {
  try {
    await HTTP.get('/user').then((response) => {
      usernameData.value = response.data;
      console.log(usernameData.value);
    })
  } catch (e) {
    console.error('Error fetching data:', e);
    // 可以在这里显示错误提示
    ElMessage({
      type: 'error',
      message: '获取数据失败，请检查网络或稍后再试。'
    });
  }
});

const form = ref({
  password: '',
  newPassword: '',
})

// 查询密保问题
const Questions = ref('')
const handleQuestions = async () => {
  try {
    const response = await HTTP.get(`/bind/question/get?username=${Questions.value}`);
    project.value = response.data;
    project.value.answer = "";
    console.log(project.value)
    if (response.code === 10200) {
      ElMessage({
        message: '查询成功',
        type: 'success',
      });

      Questions.value = '';
    } else if(response.code === 104007){
      ElMessage({
        message: '用户未设置密保,创建密保中！',
        type: 'info',
      });
      createQueDialog.value = true;
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    // 可以在这里显示错误提示
    ElMessage({
      type: 'error',
      message: '获取数据失败，请检查网络或稍后再试。'
    });
  }
}

const queNo = () => {
  createQueDialog.value = false;
  ElMessage({
    type: 'warning',
    message: '取消设置密保'
  });
}
let count = 1;
const queOk = async () => {
  try {
    const formData = new FormData();
    formData.append('jwt_token', localStorage.getItem('changeToken'));
    formData.append('question',newQue.value.que);
    formData.append('answer', newQue.value.ans);
    const response = await HTTP.post('/mupdate/question', formData);
    if (response.code === 10200) {
      if (count === 3){
        ElMessage({
          message: '设置成功',
          type:'success',
        });
      }
      else {
        count++;
        newQue.value.que = '';
        newQue.value.ans = '';
        setTimeout(() => {
          ElMessage({
            message: '设置成功，下一个问题',
            type:'success',
          });
          createQueDialog.value = true;
        }, 1000,)
      }
      createQueDialog.value = false;
    } else {
      ElMessage({
        message: '设置失败',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    // 可以在这里显示错误提示
    ElMessage({
      type: 'error',
      message: '获取数据失败，请检查网络或稍后再试。'
    });
  }
}


// 点击邮箱验证
const handleEmail = async () => {
  try {
    const response = await HTTP.post(`/bind/email/send?email=${form.value.password}`);
    console.log(response);

    if (response.code === 10200) {
      ElMessage({
        message: '验证码发送成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '验证码发送失败',
        type: 'error',
      });
    }
  } catch(error) {
    console.error('Error fetching data:', error);
  }
}

const changePass = async () => {
  try {
    const formData = new FormData();
    formData.append('jwt_token', localStorage.getItem('changeToken'));
    formData.append('password', form.value.password);
    const response = await HTTP.put('/mupdate/password', formData)
    if (response.code === 10200) {
      ElMessage({
        message: '密码修改成功',
        type:'success',
      });
    } else {
      ElMessage({
        message: '密码修改失败',
        type: 'error',
      });
    }
  }
  catch (error){
    console.error('Error fetching data:', error);
  }
}

// 修改密保
const changeQuestion = async (item) => {
  try {

    const formData = new FormData();
    formData.append('jwt_token', localStorage.getItem('changeToken'));
    formData.append('question_id', item.question_id);
    formData.append('question', item.question);
    formData.append('answer', item.answer);
    const response = await HTTP.put('/mupdate/question', formData);
    if (response.code === 10200) {
      ElMessage({
        message: '密保修改成功',
        type: 'success',
      });
      item.answer = "";
    } else {
      ElMessage({
        message: '密保修改失败',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
</script>

<template>
  <div class="account">
    <h1>
      <i class="iconfont icon-fanhui4"
         @click="handleBack"
      ></i>
    </h1>
    <h1>账号管理</h1>
    <div class="account_main">
      <div class="account_username">
        <h3>用户昵称：{{ usernameData.nickname || '暂无信息' }}</h3>
      </div>
      <div class="account_password">
        <h4>修改密码：</h4>
        <div class="flex_password">
          <el-form>
            <!-- 更换密码-->
            <div>
              <el-form-item label="新密码" label-width="140px">
                <input type="password" v-model="form.password" class="form-control" id="exampleFormControlInput1"
                       placeholder="请输入密码">
              </el-form-item>
              <el-form-item label="再次输入密码" label-width="140px">
                <input type="password" v-model="form.newPassword" class="form-control" id="exampleFormControlInput1"
                       placeholder="请输入密码">
              </el-form-item>
              <el-footer class="flex justify-end"><el-button @click="changePass">确认</el-button></el-footer>
            </div>
          </el-form>
        </div>

      </div>
      <div class="account_project">
        <h4>查看密保问题：</h4>
        <div class="flex_project">
          <input type="text" v-model="Questions" class="form-control questions"
                 placeholder="请输入账号？">
          <input class="btn btn-primary" type="submit" value="验证" @click="handleQuestions">
        </div>

        <div class="flex_questions">
          <div class="questions mb-6" v-for="item in project.securityQuestions" :key="Number(item.question_id)">
              {{ item.question }}
              <div class="flex">
              <el-input v-model="item.answer" autocomplete="off" />
              <el-button @click="changeQuestion(item)">修改</el-button>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="createQueDialog" title="创建密保" width="500">
    <el-form v-model="newQue">
      <el-form-item label="请输入问题" >
        <el-input v-model="newQue.que" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请输入答案" >
        <el-input v-model="newQue.ans" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="queNo">取消</el-button>
        <el-button type="primary" @click="queOk">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.account {
  width: 1535px;
  height: 100vh;
  margin: 0 auto;

  h1 {
    i {
      cursor: pointer;
      font-size: 40px;
      font-weight: bold;
    }
  }

  .account_main {
    width: 1200px;
    margin: 0 auto;

    .account_username {
      padding: 30px;
      width: 100%;
      border-radius: 20px;
      height: 100px;
      border: 2px dashed black;
      margin-bottom: 30px;
    }

    .account_password {
      width: 100%;
      border-radius: 20px;
      padding: 20px;
      height: 250px;
      border: 2px dashed black;
      margin-bottom: 30px;

      .flex_password {
        width: 100%;
        display: flex;
        justify-content: space-around;

        .el-form {
          width: 75%;
        }

        .btn {
          width: 150px;
          height: 50px;
          margin-top: 20px;
        }
      }
    }

    .account_project {
      width: 100%;
      height: auto;
      border-radius: 20px;
      padding: 20px;
      border: 2px dashed black;
      margin-bottom: 30px;

      .flex_project {
        width: 700px;
        margin: 20px 0;
        display: flex;
        justify-content: space-around;

        .questions {
          width: 600px;
        }
      }

      .flex_questions {
        width: 80%;
        height: auto;
        overflow-x: hidden;
        overflow-y: scroll;
        margin: 40px;

        p {
          font-weight: bold;
          font-size: 18px;
          margin-bottom: 20px;
        }
      }
    }
  }
}
</style>